<?php
/**
 * [WeEngine System] Copyright (c) 2014 WE7.CC
 * WeEngine is NOT a free software, it under the license terms, visited http://www.zzxmt.cn for more details.
 */
define('IN_MOBILE', true);
require '../../../../framework/bootstrap.inc.php';
require '../../../../addons/deam_food/common/defines.php';
require '../../../../addons/deam_food/common/functions.php';
require '../../../../addons/deam_food/common/print.class.php';

$input = file_get_contents('php://input');
$isxml = true;
if (!empty($input) && empty($_GET['out_trade_no'])) {
	$obj = isimplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);
	$res = $data = json_decode(json_encode($obj), true);
	if (empty($data)) {
		$result = array(
			'return_code' => 'FAIL',
			'return_msg' => ''
		);
		echo array2xml($result);
		exit;
	}
	if ($data['result_code'] != 'SUCCESS' || $data['return_code'] != 'SUCCESS') {
		$result = array(
			'return_code' => 'FAIL',
			'return_msg' => empty($data['return_msg']) ? $data['err_code_des'] : $data['return_msg']
		);
		echo array2xml($result);
		exit;
	}
	$get = $data;
} else {
	$isxml = false;
	$get = $_GET;
}
load()->web('common');
load()->model('mc');
load()->func('communication');
$uniacid = $_W['uniacid'] = $_W['weid'] = intval($get['attach']);
load()->func('logging');
$_W['uniaccount'] = $_W['account'] = uni_fetch($_W['uniacid']);
$_W['acid'] = $_W['uniaccount']['acid'];
$paySetting = uni_setting($_W['uniacid'], array('payment'));
if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS' ){
	$logno = trim($res['out_trade_no']);
	if (empty($logno)) {
		exit;
	}
	$log = pdo_fetch('SELECT * FROM ' . tablename('deamx_food_order') . ' WHERE `uniacid`=:uniacid and `ordersn`=:ordersn limit 1', array(
		':uniacid' => $_W['uniacid'],
		':ordersn' => $logno
	));
	$orderid = $log['id'];
	if(!empty($log) && $log['status']==0){
		$params['appid'] = $res['appid'];
		$params['mch_id'] = $res['mch_id'];
		$params['out_trade_no'] = $res['out_trade_no'];
		$wechat['apikey'] = $paySetting['payment']['wechat']['signkey'];
		$orderQueryInfo = orderquery($params,$wechat,$type);
		if($orderQueryInfo['return_code'] == 'SUCCESS' && $orderQueryInfo['result_code'] == 'SUCCESS' && $orderQueryInfo['trade_state'] == 'SUCCESS'){
			//获取门店信息
			$store_id = $log['store_id'];
			$storeInfo = pdo_get("deamx_food_store",array('uniacid'=>$_W['uniacid'],'id'=>$store_id));
			$payMoney = $orderQueryInfo['total_fee'] / 100;
			$updateArr = array(
				'status' => empty($storeInfo['auto_order']) ? '1' : '2',
				'paytime' => TIMESTAMP,
				'receivetime' => TIMESTAMP,
				'pay_price' => $payMoney
			);
			//判断是否使用免充值代金券
			if(!empty($orderQueryInfo['settlement_total_fee'])){
				$updateArr['pay_price'] = $orderQueryInfo['settlement_total_fee'] / 100;
				$updateArr['coupon_type'] = '1';
				$updateArr['coupon_price'] = $orderQueryInfo['coupon_fee'] / 100;
			}
			$updateResult = pdo_update('deamx_food_order', $updateArr, array(
				'id' => $orderid
			));
			//增加销量
			$goodsArr = json_decode($log['goods_list'],true);
			foreach ($goodsArr as $goods) {
				if($goods['count'] > 0){
					pdo_update("deamx_food_goods",array('realsales +='=>$goods['count']),array('uniacid'=>$_W['uniacid'],'id'=>$goods['goodsid']));
					if($goods['hasoption'] == '1'){
						foreach ($goods['options'] as $options) {
							if ($options['count'] > 0) {
								pdo_update("deamx_food_goods_option",array('realsales +='=>$options['count']),array('uniacid'=>$_W['uniacid'],'id'=>$options['id']));
							}
						}
					}
				}
			}
			$settings = pdo_get("deamx_food_settings",array('uniacid'=>$_W['uniacid']), array('template_status', 'template_id','sms_status','sms_type','sms_params','takeout_template_id','coupon_uniacid','deliver_dada_status','deliver_dada_app_key','deliver_dada_app_secret','deliver_dada_shopid'));
			//判断是否为外卖第三方配送 && 店铺为自动接单
			if($log['order_type'] == '2' && $storeInfo['deliver_type'] != '0' && (!empty($storeInfo['auto_order'])) ){
				if($storeInfo['deliver_type'] == '1' && $settings['deliver_dada_status'] == '1'){
					//达达配送
					require '../../../../addons/deam_food/common/imdada.class.php';
					$imdada = new Imdada_DeamFood($settings['deliver_dada_shopid'],$settings['deliver_dada_app_key'],$settings['deliver_dada_app_secret']);
					$addressinfo = json_decode($log['address_info'],true);
					$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
					$addOrder = array(
						'shop_no'	=>	$storeInfo['deliver_dada_shopno'],
						'origin_id' =>	$log['ordersn'],
						'city_code'	=>	$storeInfo['deliver_dada_citycode'],
						'cargo_price'	=>	$log['price'],
						'is_prepay'		=>	'0',
						'expected_fetch_time'	=>	TIMESTAMP + 900,
						'receiver_name'			=>	$addressinfo['realname'],
						'receiver_address'		=>	$addressinfo['address']." ".$addressinfo['address_road']." ".$addressinfo['number'],
						'receiver_lat'			=>	$addressinfo['latitude'],
						'receiver_lng'			=>	$addressinfo['longitude'],
						'callback'				=>	$http_type . $_SERVER['HTTP_HOST'].'/addons/deam_food/deliver/imdada/callback.php',
						'receiver_phone'		=>	$addressinfo['telphone']
					);
					$result = $imdada->addOrder($addOrder);
					if($result['status'] == 'success'){
						$updateResult = pdo_update('deamx_food_order', array(
							'deliver_type' => 1
						), array(
							'id' => $orderid
						));
					}else{
						$updateResult = pdo_update('deamx_food_order', array(
							'deliver_type' => -1,
							'deliver_dada_failreason' => $imdada->error_code($result['errorCode']),
						), array(
							'id' => $orderid
						));
						//记录文本日志
						logging_run($log['ordersn']);
						logging_run($result);
					}
					
				}
			}
			//判断是否使用优惠券
			//获取unionid
			$memberInfo = pdo_get("mc_mapping_fans",array('uniacid'=>$_W['uniacid'],'openid'=>$log['openid']));
			if($log['use_coupon']>0){
				$couponinfo = pdo_get("deamx_food_coupon_record",array('uniacid'=>$settings['coupon_uniacid'],'id'=>$log['use_coupon']));
				load()->classs('coupon');
				$coupon_api = new coupon($settings['coupon_uniacid']);
				
				$couponList = pdo_fetchall("SELECT r.*,c.title,c.least_cost,c.reduce_cost FROM ".tablename("deamx_food_coupon_record")." r LEFT JOIN ".tablename('deamx_food_coupon')." c ON r.card_id=c.card_id AND r.uniacid=c.coupon_uniacid WHERE c.least_cost<=:least_cost AND r.starttime<=:time AND r.endtime>=:time AND c.title!='' AND c.uniacid=:uniacid AND r.unionid=:unionid AND r.card_id=:card_id AND r.status=:status ORDER BY r.endtime ASC",array(':uniacid'=>$_W['uniacid'],':unionid'=>$memberInfo['unionid'],':least_cost'=>$log['price']*100,':time'=>$log['createtime'],':card_id'=>$couponinfo['card_id'],':status'=>'1'));
				//logging_run($couponList);
				foreach ($couponList as $key => $row) {
					$max_use = intval($log['coupon_price'] / ($row['reduce_cost']/100));
					if($key+1 <= $max_use){
						//核销卡券
						pdo_update("deamx_food_coupon_record",array('usetime'=>TIMESTAMP,'status'=>3,'order_id'=>$log['id']), array('id' => $row['id']));
						//同步核销微信卡券
						if(!empty($row['code'])){
							//获取微信
							$status = $coupon_api->ConsumeCode(array('code'=>$row['code']));
							
        					//logging_run($status);
						}
					}

				}
			}
			//判断是否赠送优惠券
			$send_rule = pdo_get("deamx_food_coupon_rules",array('starttime <='=>TIMESTAMP,'endtime >='=>TIMESTAMP,'status'=>'1','reduce_cost <='=>$payMoney));
			if(!empty($send_rule)){
				//赠送卡券
				$is_send = 0;
				if(!empty($send_rule['limit_send'])){
					//获取已经赠送的次数
					$send_count = pdo_fetchall("SELECT id FROM ".tablename('deamx_food_coupon_record')." WHERE uniacid=:uniacid AND unionid=:unionid AND rule_id=:rule_id GROUP BY source_orderid");
					$send_count = count($send_count);
					if($send_count >=$send_rule['limit_send']){
						$is_send = 1;
					}else{
						$is_send = 0;
					}
				}
				if(empty($is_send)){
					//开始赠送卡券
					$couponArr = iunserializer($send_rule['coupon_info']);
					$all_count = 0;
					foreach ($couponArr as $key => &$value) {
						$count = $value;
						// $all_count +=$count;
						$coupon_info = pdo_get("deamx_food_coupon",array('uniacid'=>$_W['uniacid'],'id'=>$key));
						$coupon_info['date_info'] = iunserializer($coupon_info['date_info']);
						if ($coupon_info['date_info']['time_type'] == 1) {
							$starttime = strtotime(str_replace(".","-",$coupon_info['date_info']['time_limit_start']));
							$endtime = strtotime(str_replace(".","-",$coupon_info['date_info']['time_limit_end']));
						} elseif($coupon_info['date_info']['time_type'] == 2) {
							if($coupon_info['date_info']['deadline'] > '0'){
								$startday = intval($coupon_info['date_info']['deadline']);
							}else{
								$startday = 0;
							}
							$starttime = strtotime(date("Y-m-d"),time()) + $startday * 24 * 60 * 60;
							$endtime = strtotime(date("Y-m-d"),time()) + $startday * 24 * 60 * 60 + $coupon_info['date_info']['limit'] * 24 * 60 * 60-1;
						}
						for ($x=1; $x<=$count; $x++) {
							$pcount = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename('deamx_food_coupon_record') . " WHERE `unionid` = :unionid AND `couponid` = :couponid", array(':couponid' => $coupon_info['id'], ':unionid' => $memberInfo['unionid']));
							if ($pcount < $coupon_info['get_limit'] && $coupon_info['quantity'] > 0) {
								$insert_data = array(
									'uniacid' => $settings['coupon_uniacid'],
									'acid' => $_W['uniacid'],
									'card_id' => $coupon_info['card_id'],
									'openid' => $log['openid'],
									'code' => '',
									'addtime' => TIMESTAMP,
									'status' => '1',
									'uid' => '',
									'grantmodule' => 'deam_food',
									'remark' => $send_rule['title'],
									'couponid' => $coupon_info['id'],
									'granttype' => 3,
									'unionid' => $memberInfo['unionid'],
									'starttime' => $starttime,
									'endtime' => $endtime,
									'rule_id' => $send_rule['id'],
									'source_orderid' => $log['id'],
								);
								$all_count ++;
								pdo_insert('deamx_food_coupon_record', $insert_data);
								pdo_update('deamx_food_coupon', array('quantity -=' => 1, 'dosage +=' => 1), array('coupon_uniacid' => $_W['uniacid'], 'id' => $coupon_info['id']));
							}
						}
						
					}
					pdo_update('deamx_food_order', array(
						'need_send_coupon' => $all_count
					), array(
						'id' => $orderid
					));
				}
			}
			//判断是否为扫桌号小程序订餐
			if(!empty($log['desk_id'])){
				$deskInfo = pdo_get("deamx_food_desknumber",array('uniacid'=>$_W['uniacid'],'id'=>$log['desk_id'],'store_id'=>$log['store_id']),array('id','name'));
			}
			
			//判断门店是否自动接单
			if(empty($storeInfo['auto_order'])){
				//
				$orderNumber = "等待接单";//等待接单
				$template_remark = "请耐心等待商家处理";
			}else{
				//非外卖订单
				if($log['order_type'] != '2'){
					//获取该门店今日已接订单数
					$todaytime = strtotime(date('Y-m-d'));
					$orderCount = pdo_fetchcolumn("SELECT COUNT(*) FROM ".tablename('deamx_food_order')." WHERE uniacid=:uniacid and store_id=:store_id and status>=2 and receivetime>=:todaytime and order_type=:order_type",array(':uniacid'=>$_W['uniacid'],':store_id'=>$store_id,':todaytime'=>$todaytime,':order_type'=>'1'));
					$orderNumber = "A".sprintf("%03d",$orderCount);//取单号
					$updateResult = pdo_update('deamx_food_order', array(
						'order_number' => $orderNumber
					), array(
						'id' => $orderid
					));
					$template_remark = TEMPLATE_REMARK;
				}
				
			}
			if($log['order_type'] != '2'){
				//获取模板消息设置
				if(!empty($settings['template_status']) && !empty($settings['template_id'])){
					load()->classs('wxapp.account');
					$accObj= WxappAccount::create($_W['uniacid']);
					$access_token = $accObj->getAccessToken();
					$templateMessageArr = array(
						'keyword1'=>array(
							'value'	=>	$orderNumber,
							'color'	=>	'#000000',
						),
						'keyword2'=>array(
							'value'	=>	'自助点餐',
							'color'	=>	'#000000',
						),
						'keyword3'=>array(
							'value'	=>	$storeInfo['name'],
							'color'	=>	'#000000',
						),
						'keyword4'=>array(
							'value'	=>	$template_remark,
							'color'	=>	'#000000',
						),
					);
					$templateMessageUrl = "deam_food/pages/order/detail?id=".$orderid;
					$messageResult = wxappMessage($access_token,$orderQueryInfo['openid'],$settings['template_id'],$templateMessageUrl,$log['prepay_id'],$templateMessageArr,"keyword1.DATA");
					//file_put_contents("messageResult.log", $messageResult);
					if($messageResult['errcode'] == '0'){
						pdo_update('deamx_food_order', array(
							'message_count +=' => '1'
						), array(
							'id' => $orderid
						));
					}
				}
			}else{
				//外卖模板消息
				if(!empty($settings['template_status']) && !empty($settings['takeout_template_id']) && !empty($storeInfo['auto_order'])){
					load()->classs('wxapp.account');
					$accObj= WxappAccount::create($_W['uniacid']);
					$access_token = $accObj->getAccessToken();
					$templateMessageArr = array(
						'keyword1'=>array(
							'value'	=>	STORE_STATUS2,
							'color'	=>	'#000000',
						),
						'keyword2'=>array(
							'value'	=>	'外卖',
							'color'	=>	'#000000',
						),
						'keyword3'=>array(
							'value'	=>	$storeInfo['name'],
							'color'	=>	'#000000',
						),
						'keyword4'=>array(
							'value'	=>	STORE_REMARK2,
							'color'	=>	'#000000',
						),
					);
					$templateMessageUrl = "deam_food/pages/order/detail?id=".$orderid;
					$messageResult = wxappMessage($access_token,$orderQueryInfo['openid'],$settings['takeout_template_id'],$templateMessageUrl,$log['prepay_id'],$templateMessageArr,"keyword1.DATA");
					//file_put_contents("messageResult.log", $messageResult);
					if($messageResult['errcode'] == '0'){
						pdo_update('deamx_food_order', array(
							'message_count +=' => '1'
						), array(
							'id' => $orderid
						));
					}
					logging_run($messageResult);
				}
			}
			if(!empty($storeInfo['auto_order'])){//接单后打印订单
				//获取打印机列表
				$printerArr = pdo_getall("deamx_food_printer",array('uniacid'=>$_W['uniacid'],'status'=>'1','store_id'=>$store_id));
				if(!empty($printerArr)){
					$print = new DeamPrint();
					$goodsArr = json_decode($log['goods_list'],true);//商品列表
					foreach ($printerArr as $printer) {
						$goodsHtml = "";
						if($printer['type'] == '4'){//易联云新
							if(empty($printer['print_type'])){//判断打印类型
								$goodsHtml = '<tr><td>品名</td><td>数量</td><td>小计</td></tr>';
								foreach ($goodsArr as $index => $goodsInfo) {
									if(empty($goodsInfo['hasoption']) && $goodsInfo['count']>0){
										if($index >0){
											$goodsHtml .= "<tr><td></td></tr>";
										}
										$goodsHtml .= "<tr><td>".$goodsInfo['name']."</td><td>".$goodsInfo['count']."</td><td>".$goodsInfo['totalprice']."</td></tr>";
									}else{
										if(is_array($goodsInfo['options'])){
											foreach ($goodsInfo['options'] as $optionsIndex => $optionsInfo) {
												if($optionsInfo['count']>0){
													if($index > 0 || $optionsIndex > 0){
														$goodsHtml .= "<tr><td></td></tr>";
													}
													$goodsHtml .= "<tr><td>".$goodsInfo['name']."</td><td>".$optionsInfo['count']."</td><td>".$optionsInfo['price']."</td></tr>";
													$goodsHtml .= "<tr><td>".$optionsInfo['name']."</td></tr>";
												}
											}
										}
									}
								}
								$times = (empty($printerConf['printer_yilianyun_new']['times'])||$printerConf['printer_yilianyun_new']['times']=='1') ? '':"<MN>".$printerConf['printer_yilianyun_new']['times']."</MN>";
								if($log['order_type'] != '2'){
									$printTemp = "\r\n\r\n取餐号 <FS2>".$orderNumber."</FS2>".(empty($deskInfo['name'])?'':"\r\n\r\n桌号 <FS2>".$deskInfo['name']."</FS2>");
								}else{
									$printTemp = "\r\n\r\n订单号".$log['ordersn'];
									$goodsHtml .= "<tr><td></td></tr>";
									$goodsHtml .= "<tr><td>餐盒费</td><td> </td><td>".$log['pbox_fee']."</td></tr>";
									$goodsHtml .= "<tr><td></td></tr>";
									$goodsHtml .= "<tr><td>配送费</td><td> </td><td>".$log['send_fee']."</td></tr>";
								}
								$printerConf = json_decode($printer['print_data'],true);
								$content = $times."<FB><center>".$storeInfo['name']."</center></FB>".$printTemp."\r\n\r\n<table>".$goodsHtml ."</table><table><tr><td></td></tr><tr><td>合计</td><td>".$log['count']."</td><td>".$log['price']."</td></tr></table>\r\n\r\n支付时间：".date('Y-m-d H:i:s').($log['enoughdeduct'] > 0 ? "\r\n满减优惠：".$log['enoughdeduct']."元":'').($log['coupon_price'] > 0 ? "\r\n优惠券优惠：".$log['coupon_price']."元":'')."\r\n实际支付：".$payMoney."元\r\n<FB>备注：".$log['remark']."</FB>\r\n";
								if($log['order_type'] == '2'){
									$addressinfo = json_decode($log['address_info'],true);
									$content .= "\r\n<FS2>".$addressinfo['realname']." ".$addressinfo['telphone']."</FS2>\r\n<FS2>".$addressinfo['address']." ".$addressinfo['address_road']." ".$addressinfo['number']."</FS2>\r\n";
								}
							}else{
								//分单打印
								foreach ($goodsArr as $index => $goodsInfo) {
									//获取商品分类
									$goodsClass = pdo_getcolumn("deamx_food_goods",array('uniacid'=>$uniacid,'id'=>$goodsInfo['goodsid']), 'class_id',1);
									$print_class = json_decode($printer['print_class'],true);
									if(@in_array($goodsClass, $print_class)){
										if(empty($goodsInfo['hasoption']) && $goodsInfo['count']>0){
											$x = 1;
											while($x <= $goodsInfo['count']){
												if($log['order_type'] != '2'){
													$goodsHtml .= "取餐号 <FS2>".$orderNumber."</FS2>".(empty($deskInfo['name'])?'':"\r\n\r\n桌号 <FS2>".$deskInfo['name']."</FS2>")."\r\n\r\n";
												}else{
													$goodsHtml .= "订单号 <FB>".$log['ordersn']."</FB>\r\n\r\n";
												}
												
												$goodsHtml .= "<FS2>".$goodsInfo['name']." x1</FS2>\r\n\r\n<FB>备注：".$log['remark']."</FB>\r\n\r\n";
												$x++;
											}
										}else{
											if(is_array($goodsInfo['options'])){
												foreach ($goodsInfo['options'] as $optionsIndex => $optionsInfo) {
													if($optionsInfo['count']>0){
														$x = 1;
														while($x <= $optionsInfo['count']){
															if($log['order_type'] != '2'){
																$goodsHtml .= "取餐号 <FS2>".$orderNumber."</FS2>".(empty($deskInfo['name'])?'':"\r\n\r\n桌号 <FS2>".$deskInfo['name']."</FS2>")."\r\n\r\n";
															}else{
																$goodsHtml .= "订单号 <FB>".$log['ordersn']."</FB>\r\n\r\n";
															}
															$goodsHtml .= "<FS2>".$goodsInfo['name']."-".$optionsInfo['name']." x1</FS2>\r\n\r\n<FB>备注：".$log['remark']."</FB>\r\n\r\n";
															$x++;
														}
													}
												}
											}
										}
									}
									
								}
								$printerConf = json_decode($printer['print_data'],true);
								$content = ((empty($printerConf['printer_yilianyun_new']['times'])||$printerConf['printer_yilianyun_new']['times']=='1') ? '':"<MN>".$printerConf['printer_yilianyun_new']['times']."</MN>").$goodsHtml;
							}
							$apiKey = $printerConf['printer_yilianyun_new']['apikey'];
							$msign = $printerConf['printer_yilianyun_new']['msign'];
							$result = $print->printerYilianyunNew($printerConf['printer_yilianyun_new']['url'],$printerConf['printer_yilianyun_new']['partner'],$printerConf['printer_yilianyun_new']['machine_code'],$content,$apiKey,$msign);
						}elseif($printer['type'] == '1'){//飞鹅
							if(empty($printer['print_type'])){//判断打印类型
								$content = "<C>".$storeInfo['name']."</C><BR><BR>";
								if($log['order_type'] != '2'){
									$content .= "取餐号 <B>".$orderNumber."</B><BR><BR>";
									if(!empty($deskInfo['name'])){
										$content .= "桌号 <B>".$deskInfo['name']."</B><BR>";
									}
								}else{
									$content .= "订单号 <B>".$log['ordersn']."</B><BR>";
								}
								$content .= setSpacing("品名",22).setSpacing("数量",5).setSpacing("金额",5).'<BR>';
								$content .= '--------------------------------<BR>';
								foreach ($goodsArr as $index => $goodsInfo) {
									if(empty($goodsInfo['hasoption']) && $goodsInfo['count']>0){
										if($index >0){
											$content .= "<BR>";
										}
										$content .= setSpacing($goodsInfo['name'],22).setSpacing($goodsInfo['count'],5).setSpacing($goodsInfo['totalprice'],5)."<BR>";
									}else{
										if(is_array($goodsInfo['options'])){
											foreach ($goodsInfo['options'] as $optionsIndex => $optionsInfo) {
												if($optionsInfo['count']>0){
													if($index > 0 || $optionsIndex > 0){
														$content .= "<BR>";
													}
													$content .= setSpacing($goodsInfo['name'],22).setSpacing($optionsInfo['count'],5).setSpacing($optionsInfo['price'],5)."<BR>";
													$content .= $optionsInfo['name']."<BR>";
												}
											}
										}
									}
								}
								if($log['order_type'] == '2'){
									if($log['pbox_fee'] > 0){
										$content .= setSpacing("餐盒费",22).setSpacing("",5).setSpacing($log['pbox_fee'],5).'<BR>';
									}
									$content .= setSpacing("配送费",22).setSpacing("",5).setSpacing($log['send_fee'],5).'<BR>';
								}
								$content .= '--------------------------------<BR>';
								$printerConf = json_decode($printer['print_data'],true);
								$content .= "支付时间：".date('Y-m-d H:i:s')."<BR><BR>";
								if($log['enoughdeduct'] > 0){
									$content .= "满减优惠：".$log['enoughdeduct']."元<BR><BR>";
								}
								if($log['coupon_price'] > 0){
									$content .= "优惠券优惠：".$log['coupon_price']."元<BR><BR>";
								}
								$content .= "实际支付：".$payMoney."元<BR><BR>";
								$content .= "<B>备注：".$log['remark']."</B><BR>";
								if($log['order_type'] == '2'){
									$addressinfo = json_decode($log['address_info'],true);
									$content .= "<BR><B>".$addressinfo['realname']." ".$addressinfo['telphone']."</B><B>".$addressinfo['address']." ".$addressinfo['address_road']." ".$addressinfo['number']."</B><BR>";
								}
								$content .= '<BR>';
							}else{
								$printerConf = json_decode($printer['print_data'],true);
								//分单打印
								$content = '';
								foreach ($goodsArr as $index => $goodsInfo) {
									//获取商品分类
									$goodsClass = pdo_getcolumn("deamx_food_goods",array('uniacid'=>$uniacid,'id'=>$goodsInfo['goodsid']), 'class_id',1);
									$print_class = json_decode($printer['print_class'],true);
									if(@in_array($goodsClass, $print_class)){
										if(empty($goodsInfo['hasoption']) && $goodsInfo['count']>0){
											$x = 1;
											while($x <= $goodsInfo['count']){
												if($log['order_type'] != '2'){
													$content .= "取餐号 <B>".$orderNumber."</B>".(empty($deskInfo['name'])?'':"<BR><BR>桌号 <B>".$deskInfo['name']."</B>")."<BR><BR>";
												}else{
													$content .= "订单号 <B>".$log['ordersn']."</B><BR>";
												}
												$content .= "<B>".$goodsInfo['name']." x1</B><BR><BR><B>备注：".$log['remark']."</B><BR><BR>";
												$x++;
											}
										}else{
											if(is_array($goodsInfo['options'])){
												foreach ($goodsInfo['options'] as $optionsIndex => $optionsInfo) {
													if($optionsInfo['count']>0){
														$x = 1;
														while($x <= $optionsInfo['count']){
															if($log['order_type'] != '2'){
																$content .= "取餐号 <B>".$orderNumber."</B>".(empty($deskInfo['name'])?'':"<BR><BR>桌号 <B>".$deskInfo['name']."</B>")."<BR><BR>";
															}else{
																$content .= "订单号 <B>".$log['ordersn']."</B><BR>";
															}
															$content .= "<B>".$goodsInfo['name']."-".$optionsInfo['name']." x1</B><BR><BR><B>备注：".$log['remark']."</B><BR><BR>";
															$x++;
														}
													}
												}
											}
										}
									}
									
								}
							}
							$result = $print->printerFeie($printerConf['printer_feie']['url'],$printerConf['printer_feie']['user'],$printerConf['printer_feie']['ukey'],$printerConf['printer_feie']['deviceNo'],$content,$printerConf['printer_feie']['times']);
						
						}elseif($printer['type'] == '2'){//365 s1
							$printerConf = json_decode($printer['print_data'],true);
							if(empty($printer['print_type'])){//判断打印类型
								$content = empty($printerConf['printer_365s1']['times']) ? '^N1^F1' . "\n" : '^N' . $printerConf['printer_365s1']['times'] . '^F1' . "\n";
								$content .= $storeInfo['name']."\n\n";
								if($log['order_type'] != '2'){
									$content .= "^H2取餐号 ".$orderNumber."\n\n";
									if(!empty($deskInfo['name'])){
										$content .= "^H2桌号 ".$deskInfo['name']."\n\n";
									}
								}else{
									$content .= "订单号 ".$log['ordersn']."\n";
								}
								$content .= setSpacing("品名",22).setSpacing("数量",5).setSpacing("金额",5)."\n";
								$content .= "--------------------------------\n";
								foreach ($goodsArr as $index => $goodsInfo) {
									if(empty($goodsInfo['hasoption']) && $goodsInfo['count']>0){
										if($index >0){
											$content .= "\n";
										}
										$content .= setSpacing($goodsInfo['name'],22).setSpacing($goodsInfo['count'],5).setSpacing($goodsInfo['totalprice'],5)."\n";
									}else{
										if(is_array($goodsInfo['options'])){
											foreach ($goodsInfo['options'] as $optionsIndex => $optionsInfo) {
												if($optionsInfo['count']>0){
													if($index > 0 || $optionsIndex > 0){
														$content .= "\n";
													}
													$content .= setSpacing($goodsInfo['name'],22).setSpacing($optionsInfo['count'],5).setSpacing($optionsInfo['price'],5)."\n";
													$content .= $optionsInfo['name']."\n";
												}
											}
										}
									}
								}
								if($log['order_type'] == '2'){
									if($log['pbox_fee'] > 0){
										$content .= setSpacing("餐盒费",22).setSpacing("",5).setSpacing($log['pbox_fee'],5)."\n";
									}
									$content .= setSpacing("配送费",22).setSpacing("",5).setSpacing($log['send_fee'],5)."\n";
								}
								$content .= "--------------------------------\n";
								
								$content .= "支付时间：".date('Y-m-d H:i:s')."\n\n";
								if($log['enoughdeduct'] > 0){
									$content .= "满减优惠：".$log['enoughdeduct']."元\n\n";
								}
								if($log['coupon_price'] > 0){
									$content .= "优惠券优惠：".$log['coupon_price']."元\n\n";
								}
								$content .= "实际支付：".$payMoney."元\n\n";
								$content .= "^H2备注：".$log['remark']."\n";
								if($log['order_type'] == '2'){
									$addressinfo = json_decode($log['address_info'],true);
									$content .= "\n^H2".$addressinfo['realname']." ".$addressinfo['telphone']."\n^H2".$addressinfo['address']." ".$addressinfo['address_road']." ".$addressinfo['number']."\n";
								}
							}else{
								$printerConf = json_decode($printer['print_data'],true);
								//分单打印
								$content = '';
								foreach ($goodsArr as $index => $goodsInfo) {
									//获取商品分类
									$goodsClass = pdo_getcolumn("deamx_food_goods",array('uniacid'=>$uniacid,'id'=>$goodsInfo['goodsid']), 'class_id',1);
									$print_class = json_decode($printer['print_class'],true);
									if(@in_array($goodsClass, $print_class)){
										if(empty($goodsInfo['hasoption']) && $goodsInfo['count']>0){
											$x = 1;
											while($x <= $goodsInfo['count']){
												if($log['order_type'] != '2'){
													$content .= "^H2取餐号 ".$orderNumber."\n";
													if(!empty($deskInfo['name'])){
														$content .= "^H2桌号 ".$deskInfo['name']."\n";
													}
												}else{
													$content .= "订单号 ".$log['ordersn']."\n";
												}
												$content .= "^H2".$goodsInfo['name']." x1\n";
												$content .= "^H2备注：".$log['remark']."\n\n";
												$x++;
											}
										}else{
											if(is_array($goodsInfo['options'])){
												foreach ($goodsInfo['options'] as $optionsIndex => $optionsInfo) {
													if($optionsInfo['count']>0){
														$x = 1;
														while($x <= $optionsInfo['count']){
															if($log['order_type'] != '2'){
																$content .= "^H2取餐号 ".$orderNumber."\n";
																if(!empty($deskInfo['name'])){
																	$content .= "^H2桌号 ".$deskInfo['name']."\n";
																}
															}else{
																$content .= "订单号 ".$log['ordersn']."\n";
															}
															$content .= "^H2".$goodsInfo['name']."-".$optionsInfo['name']." x1\n";
															$content .= "^H2备注：".$log['remark']."\n\n";
															$x++;
														}
													}
												}
											}
										}
									}
									
								}
							}
							$result = $print->printer365s1($printerConf['printer_365s1']['deviceNo'],$printerConf['printer_365s1']['key'],$content,$printerConf['printer_365s1']['times']);
						}
					}
				}
			}
			//短信通知商家
			if(!empty($settings['sms_status']) && !empty($storeInfo['notice_tel'])){
				$settings['sms_params'] = json_decode($settings['sms_params'],true);
				if($settings['sms_type'] == '1'){//阿里云接口
					date_default_timezone_set('GMT');
					$postdate = array();
					//系统参数
					$postdate['SignatureMethod'] = 'HMAC-SHA1';
					$postdate['SignatureNonce'] = uniqid();
					$postdate['AccessKeyId'] = $settings['sms_params']['ali']['appkey'];
					$postdate['SignatureVersion'] = '1.0';
					$postdate['SignatureVersion'] = '1.0';
					$postdate['Timestamp'] = date('Y-m-d\TH:i:s\Z');
					$postdate['Format'] = "JSON";
					//业务API参数
					$postdate['Action'] = "SendSms";
					$postdate['Version'] = "2017-05-25";
					$postdate['RegionId'] = "cn-hangzhou";
					$postdate['PhoneNumbers'] = $storeInfo['notice_tel'];
					$postdate['SignName'] = $settings['sms_params']['ali']['signname'];
					$postdate['TemplateParam'] = '{"storename":"'.$storeInfo['name'].'"}';
					$postdate['TemplateCode'] = $settings['sms_params']['ali']['templateCode'];
					$postdate['OutId'] = $extend;
					$unSignParaStr = formatQueryParaMap($postdate,true);
					$unSignParaStr = str_replace("+", "%20",$unSignParaStr);
					$unSignParaStr = str_replace("*", "%2A",$unSignParaStr);
					$unSignParaStr = str_replace("%7E", "~",$unSignParaStr);
					//二次转换
					$tempStr = urlencode($unSignParaStr);
					$tempStr = str_replace("+", "%20",$tempStr);
					$tempStr = str_replace("*", "%2A",$tempStr);
					$tempStr = str_replace("%7E", "~",$tempStr);
					$tempStr = "GET&".urlencode("/")."&".$tempStr;
					$sign = getSignature($tempStr,$settings['sms_params']['ali']['secret']."&");
					//特殊urlencode转换sign
					$sign = urlencode($sign);
					$sign = str_replace("+", "%20",$sign);
					$sign = str_replace("*", "%2A",$sign);
					$sign = str_replace("%7E", "~",$sign);
					$unSignParaStr = "Signature=".$sign."&".$unSignParaStr;
					$postUrl = "http://dysmsapi.aliyuncs.com/?".$unSignParaStr;
					$recode = httpcurl($postUrl);
					
					$return = json_decode($recode,true);
					if($return['Code'] == 'OK'){
						
					}else{
						file_put_contents("message_tel.txt", $recode);
					}
				}
			}
			$result = array(
				'return_code' => 'SUCCESS',
				'return_msg' => 'OK'
			);
			echo array2xml($result);
			exit;
		}
	}else{
		//订单已经处理过了
		$result = array(
			'return_code' => 'SUCCESS',
			'return_msg' => 'OK'
		);
		echo array2xml($result);
		exit;
	}
}